﻿/// <summary>
/// 作者：江怀玉
/// 日期：2011-10-12
/// 公司：iSun 软件工作室
/// 描述：业务处理基类,提供常用的操作方法
/// 
/// </summary>
using System;
using System.Collections.Generic;
using System.Linq;
using iSun.Model;
using System.Data;
using System.Data.SqlClient;
namespace iSun.BLL.Base
{

    public  class BaseBussnies
    {
        public BaseBussnies(BaseEntity entitys)
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
            entity = entitys;
        }
        public BaseEntity entity
        {
            get;
            set;
        }

        public BaseBussnies() { }

        /// <summary>
        /// 新增实体数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool Insert(object entitys)
        {
            this.entity = entitys as BaseEntity;
            iSun.SPL.Factory.DialectFactory DF = iSun.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Save();
        }


        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="entitys">实体对象</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public virtual bool Insert(object entitys, out string msg)
        {
            msg = "";
            try
            {
                return Insert(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }


        /// <summary>
        /// 新增实体数据
        /// </summary>
        public virtual bool Insert()
        {
            return Insert(entity);
        }

        public virtual bool Insert(out string msg)
        {
            return Insert(entity, out msg);
        }
        /// <summary>
        /// 更新实体数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool Update(object entitys)
        {
            iSun.SPL.Factory.DialectFactory DF = iSun.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Update();
        }
        /// <summary>
        /// 更新实体数据
        /// </summary>
        public virtual bool Update()
        {
            return Update(entity);
        }

        public virtual bool Update(out string msg)
        {
            return Update(entity, out msg);
        }


        /// <summary>
        /// 更新操作
        /// </summary>
        /// <param name="entitys">实体对象</param>
        /// <param name="msg">错误消息</param>
        /// <returns>执行成功与否</returns>
        public virtual bool Update(object entitys, out string msg)
        {
            msg = "";
            try
            {
                return Update(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }

        /// <summary>
        /// 删除实体的数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool delete(object entitys)
        {
            iSun.SPL.Factory.DialectFactory DF = iSun.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Delete();
        }
        /// <summary>
        /// 删除实体的数据
        /// </summary>
        public virtual bool delete()
        {
            return delete(entity);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entitys"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public virtual bool delete(object entitys, out string msg)
        {
            msg = "";
            try
            {
                return delete(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }

        /// <summary>
        /// 删除操作
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns></returns>
        public virtual bool delete(string condition)
        {
            iSun.SPL.Factory.DialectFactory DF = iSun.SPL.Factory.Dialects.GetDialect(entity);
            return DF.Delete(condition);
        }

        /// <summary>
        /// 批量保存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        public void BatchSave<T>(IList<T> list) where T:BaseEntity
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder("");
            iSun.SPL.Factory.DialectFactory DF = iSun.SPL.Factory.Dialects.GetDialect<T>();
            if (list != null)
            {
                foreach (T t in list)
                {
                    DF.Entitys = t;
                    sb.Append(DF.GetSqlCommand());
                    // this.getsq
                }
            }
            if (sb.Length == 0)
            {
                return;
            }
            DF.BatchSave(sb.ToString());
        }

        /// <summary>
        /// 批量保存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        public void BatchSave(IList<BaseEntity> list)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder("");
            iSun.SPL.Factory.DialectFactory DF = iSun.SPL.Factory.Dialects.GetDialect(null);
            if (list != null)
            {
                foreach (BaseEntity t in list)
                {
                    DF.Entitys = t;
                    sb.Append(DF.GetSqlCommand());
                    // this.getsq
                }
            }
            if (sb.Length == 0)
            {
                return;
            }
            DF.BatchSave(sb.ToString());
        }

        /// <summary>
        /// 通过ID获取实体
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>实体</returns>
        public virtual  BaseEntity GetEntityById(object id)
        {
            if (id.ToString() == "" || id == null)
            {
                return null;
            }
            else
            {
                try
                {
                    iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.Dialects.GetDialect(this.entity);
                    string _strSel = df.SelectCommand(id);
                    return GetEntityBySqlComm(_strSel) as BaseEntity;
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitysSplitPage(string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
            string SqlComm = string.Empty;
            try
            {
                string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order;
                order = string.IsNullOrEmpty(order) ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (  SELECT ROW_NUMBER() OVER" + order + " AS RowNumber,* FROM " + this.entity.getTableName() + (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize;
                //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                iSun.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                om.SqlComm = SqlComm;
                return om.DatatableToObject();
            }
            catch (System.Exception ex)
            {
                return null;
            }

        }

        public virtual System.Data.DataSet GetDataSet(string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
            string SqlComm = string.Empty;
            try
            {
                string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order;
                order = string.IsNullOrEmpty(order) ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                SqlComm = "SELECT * FROM " + this.entity.getTableName() + (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize;
                //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                iSun.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                om.SqlComm = SqlComm;
                return om.GetDataSetBySqlComm();
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }

        public virtual System.Data.DataTable GetDataTableSplitPage(string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
            string SqlComm = string.Empty;
            try
            {
                string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order;
                order = string.IsNullOrEmpty(order) ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (  SELECT ROW_NUMBER() OVER" + order + " AS RowNumber,* FROM " + this.entity.getTableName() + (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize;
                //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                iSun.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                om.SqlComm = SqlComm;
                return om.GetDataBySqlComm();
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }


        public virtual System.Data.DataTable GetDTByTable(string TableName)
        {
            return null;
        }
        /// <summary>
        /// 根据不同实体实例化业务实例
        /// 用于实现的不同的实体调用不同的业务逻辑
        /// </summary>
        /// <param name="entityName"></param>
        /// <returns></returns>
        public static BaseBussnies CreateInstance(string entityName)
        {
            Model.Entity entity = (new BaseBussnies()).GetEntityByCondition<Model.Entity>("entityName='" + entityName + "'");
            if (entity != null)
            {
                if (entity.BLLConfig != null)
                {
                    try
                    {
                        string[] str = entity.BLLConfig.Split(',');
                        return Common.Reflection.CreateInstance(str[0], str[1]) as BaseBussnies;
                    }
                    catch { }
                }
            }
            return new BaseBussnies();

        }

        public virtual T GetEntityById<T>(int id)
        {
            BaseEntity be = default(T) as BaseEntity;
            return GetEntityByCondition<T>(be.GetTableId() + "=" + id);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual IList<T> GetEntityListByCondition<T>(string Condition)
        {
            Condition = String.IsNullOrEmpty(Condition) ? "1=1" : Condition;
            if (Condition == null || Condition == string.Empty)
            {
                return null;
            }
            else
            {
                iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.DialectFactory.instance(this.entity);
                return this.GetEntitysBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
            }
        }


        ///// <summary>
        ///// 获取需要自动保存的字段列表
        ///// </summary>
        ///// <param name="tableName">表名或者实体名</param>
        ///// <returns></returns>
        //public IList<EditUIConfig> GetSysAutoSaveFieldList(string tableName)
        //{
        //    return GetEntitysByCondition<EditUIConfig>("EntityName='" + tableName + "' and IsSysAutoSave='Y'");
        //}

        /// <summary>
        /// 通过SqlComm命令获取实体
        /// </summary>
        /// <param name="SqlComm">Sql Command</param>
        /// <returns>实体</returns>
        public virtual object GetEntityBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    iSun.SPL.ORM.ObjectMapper om = new iSun.SPL.ORM.ObjectMapper(entity);
                    om.SqlComm = SqlComm;
                    return om.DataTableToObject();
                }
                catch
                {
                    return null;
                }
            }
        }
        public virtual T GetEntityById<T>(Guid id)
        {

            return default(T);
        }
        public virtual T GetEntityBySqlComm<T>(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return default(T);
            }
            else
            {
                try
                {
                    object o;
                    o = System.Activator.CreateInstance<T>();
                    //if (this.entity is DataTableBaseEntity)
                    //{
                    //    o = System.Activator.CreateInstance<T>() as BaseEntity;
                    //}
                    //else
                    //{
                    //    o = this.entity;
                    //}
                    iSun.SPL.ORM.ObjectMapper om = new iSun.SPL.ORM.ObjectMapper(o,SqlComm);
                    om.SqlComm = SqlComm;
                    return (T)om.DataTableToObject();
                }
                catch
                {
                    return default(T);
                }
            }
        }
        /// <summary>
        /// 通过SqlComm命令获取实体
        /// </summary>
        /// <param name="SqlComm">Sql Command</param>
        /// <returns>实体</returns>
        public virtual IList<BaseEntity> GetEntitysBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    order = order == "" ? " " : order + (this.Desc == "Yes" ? "  Desc " : " Asc");
                    iSun.SPL.ORM.ObjectMapper om = new iSun.SPL.ORM.ObjectMapper(entity);

                    om.SqlComm = SqlComm + " " + order;
                    return om.DatatableToObject();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 直接通过sql命令
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="SqlComm"></param>
        /// <returns></returns>
        public virtual IList<T> GetEntitysBySqlComm<T>(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc " : " Asc");
                    iSun.SPL.ORM.TObject<T> om = new iSun.SPL.ORM.TObject<T>(SqlComm);
                    om.SqlComm = SqlComm + " " + order;
                    return om.DatatableToObject<T>();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }


        public IList<TableInfoStruc> GetTableInfoStruc(string tableName)
        {
            return this.GetEntitysBySqlComm<TableInfoStruc>("select * from V_TableInfoStruc where TableName='" + tableName + "'");
        }

        /// <summary>
        /// 获取表关键字段
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public string GetTableKey(string tableName)
        {
            var o = this.GetEntitysBySqlComm<TableInfoStruc>("select * from V_TableInfoStruc where TableName='" + tableName + "' and Substring(PKey,1,1)='Y'");
            if (o == null)
            {
                return this.GetEntitysByCondition<DataListTemplate>("EntityName='" + tableName + "'").First().Field;
            }
            return (o == null) ? "ID" : o.First().ColName;

        }

        /// <summary>
        /// 根据表结构，生成DataTable结构
        /// </summary>
        /// <param name="tableName">表名 </param>
        /// <returns></returns>
        public System.Data.DataTable CreateDataTable(string tableName)
        {
            IList<TableInfoStruc> tfList = GetTableInfoStruc(tableName);
            System.Data.DataTable dt = new System.Data.DataTable();
            foreach (TableInfoStruc tifs in tfList)
            {
                dt.Columns.Add(tifs.TableName, iSun.Common.Globals.CovertDBType(tifs.CType));
            }
            return dt;
        }

        /// <summary>
        /// 根据表结构，生成DataTable结构
        /// </summary>
        /// <param name="tableName">表名 </param>
        /// <param name="tf">表结构列表</param>
        /// <returns></returns>
        public System.Data.DataTable CreateDataTable(string tableName,out IList<TableInfoStruc> tf)
        {
            IList<TableInfoStruc> tfList = GetTableInfoStruc(tableName);
            System.Data.DataTable dt = new System.Data.DataTable();
            foreach (TableInfoStruc tifs in tfList)
            {
                dt.Columns.Add(tifs.ColName, iSun.Common.Globals.CovertDBType(tifs.CType));
            }
            tf = tfList;
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="Json"></param>
        /// <returns></returns>
        public virtual System.Data.DataTable GetSingleRowDT(string tableName, string Json)
        {
            Dictionary<string, object> JsonData = iSun.Common.Globals.ConvertToDictionary(Json);
            IList<TableInfoStruc> tf;
            System.Data.DataTable dt = CreateDataTable(tableName,out tf);
            System.Data.DataRow dr = dt.NewRow();
            foreach (KeyValuePair<string, object> field in JsonData)
            {
                string FType = tf.Where(p => p.ColName == field.Key).Select(p => p.CType).FirstOrDefault();
                dr[field.Key] = iSun.Common.Globals.CovertValue(FType,field.Value as string);
            }
            dt.Rows.Add(dr);
            return dt;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetAllEntitys()
        {
            iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.Dialects.GetDialect(this.entity);
            return this.GetEntitysBySqlComm(df.SelectAllCommand());
        }
        public virtual IList<T> GetAllEntitys<T>()
        {
            iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.DialectFactory.instance<T>();
            return this.GetEntitysBySqlComm<T>(df.SelectAllCommand());
        }
        //public IList<T> GetEntitys<T>()
        //{
        //    ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(this.entity);
        //    return this.GetEntitysBySqlComm(df.SelectAllCommand());
        //}

        /// <summary>
        /// 通过条件获取数据对象
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns>数据对象列表</returns>
        public virtual IList<BaseEntity> GetEntitysByCondition(string Condition)
        {
            if (Condition == null || Condition == string.Empty)
            {
                return GetAllEntitys();
            }
            else
            {
                iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.Dialects.GetDialect(entity);
                IList<BaseEntity> entitys= this.GetEntitysBySqlComm(df.SelectAllCommand() + " where " + Condition);
                return entitys;
            }
        }

        /// <summary>
        /// 通过条件获取数据对象
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns>数据对象列表</returns>
        public virtual IList<T> GetEntitysByCondition<T>(string Condition)
        {
            if (Condition == null || Condition == string.Empty)
            {
                return GetAllEntitys<T>();
            }
            else
            {
                iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.DialectFactory.instance<T>();
                return this.GetEntitysBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
            }
        }


        /// <summary>
        /// 获取实体列表
        /// </summary>
        /// <returns>当前全部实体温表对象</returns>
        public virtual IList<BaseEntity> GetEntitys()
        {
            iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.Dialects.GetDialect(this.entity);
            return this.GetEntitysBySqlComm(df.SelectAllCommand());
        }
        /// <summary>
        /// 获取实体列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual IList<T> GetEntitys<T>()
        {
            iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.DialectFactory.instance<T>();
            return this.GetEntitysBySqlComm<T>(df.SelectAllCommand());
        }
        //public IList<T> GetEntitys<T>()
        //{
        //    ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(this.entity);
        //    return this.GetEntitysBySqlComm(df.SelectAllCommand());
        //}
        /// <summary>
        /// 获取实体列表
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns>实体对象列表</returns>
        public virtual IList<BaseEntity> GetEntitys(string Condition)
        {
            if (Condition == null || Condition == string.Empty)
            {
                return GetEntitys();
            }
            else
            {
                iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.Dialects.GetDialect(entity);
                IList<BaseEntity> entitys = this.GetEntitysBySqlComm(df.SelectAllCommand() + " where " + Condition);
                return entitys;
            }
        }
        public virtual IList<T> GetEntitys<T>(string Condition)
        {
            if (Condition == null || Condition == string.Empty)
            {
                return GetEntitys<T>();
            }
            else
            {
                iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.DialectFactory.instance<T>();
                return this.GetEntitysBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
            }
        }

        /// <summary>
        /// 生成XML文件
        /// </summary>
        /// <param name="SqlComm"></param>
        /// <returns></returns>
        public virtual string BuildXmlFile(string SqlComm)
        {
            iSun.SPL.ORM.ObjectMapper om = new iSun.SPL.ORM.ObjectMapper(new object(), SqlComm);
            return om.BuildXmlFile();
        }
        /// <summary>
        /// 数据实体数组
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitysByIds(string[] id)
        {
            if (id.Length == 0)
            {
                return null;
            }

            IList<BaseEntity> al = new List<BaseEntity>();
            for (int i = 0; i < id.Length - 1; i++)
            {
                BaseEntity obj = GetEntityById(id[i]);
                al.Add(obj);
            }
            return al;
        }
        //public IList<T> GetEntitysByIds<T>(string[] id)
        //{
        //    if (id.Length == 0)
        //    {
        //        return null;
        //    }

        //    ArrayList al = new ArrayList();
        //    for (int i = 0; i < id.Length - 1; i++)
        //    {
        //        object obj = GetEntityById(id[i]);
        //        al.Add(obj);
        //    }
        //    return al.ToArray();
        //}
        /// <summary>
        /// 通过条件获取实体
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns>实体</returns>
        public virtual object GetEntityByCondition(string Condition)
        {
            iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.Dialects.GetDialect(entity);
            return this.GetEntityBySqlComm(df.SelectAllCommand() + " where " + Condition);
        }
        public virtual T GetEntityByCondition<T>(string Condition)
        {
            iSun.SPL.Factory.DialectFactory df = iSun.SPL.Factory.DialectFactory.instance<T>();
            return this.GetEntityBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
        }


        [Obsolete("不要再override此方法了", false)]
        public virtual string CheckData(BaseEntity entity)
        {
            return "";
        }

        public virtual string CheckData()
        {
            return "";
        }

        public virtual string EditCheckData()
        {
            return "";
        }

        public virtual string DeleteCheckData()
        {
            return "";
        }
        /// <summary>
        /// 获取插入更新的Sql Command
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public virtual string GetSqlCommand(BaseEntity entity)
        {
            iSun.SPL.Factory.DialectFactory DF = iSun.SPL.Factory.Dialects.GetDialect(entity);
            return DF.GetSqlCommand();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DataType"></param>
        /// <returns></returns>
        public bool IsEmpty(object obj, string DataType)
        {
            if (obj == null)
            {
                return true;
            }

            if (DataType.IndexOf("String") == 0)
            {
                if ((string)obj == string.Empty)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 获取唯一标识符
        /// </summary>
        /// <returns></returns>
        public string GetGuids()
        {
            if (this.entity is DataTableBaseEntity)
            {
                DataTableBaseEntity table = ((DataTableBaseEntity)this.entity);
                if(!string.IsNullOrEmpty(((DataTableBaseEntity)this.entity).TableKey))
                {
                    return table.TableKey;
                }
                else
                {
                    TableInfoStruc entity = this.GetEntityByCondition<TableInfoStruc>("TableName='"+table.TableName+"' and Substring(PKey,1,1)='Y'");
                    if (entity == null)
                    {
                        this.Order = "iOrder";
                        this.Desc = "No";
                        return this.GetEntitysByCondition<DataListTemplate>("EntityName='" + table.TableName + "'").First().Field;
                    }
                    return entity.ColName;
                }
            }
            else
            {
                Type t = this.entity.GetType();
                foreach (Attribute attr in t.GetCustomAttributes(true))
                {
                    iSun.Model.TableAttribute tableattribute = attr as iSun.Model.TableAttribute;
                    if (null != tableattribute)
                    {
                        return tableattribute.Guid;
                    }
                }
                return "";
            }
        }

        /// <summary>
        /// 获取表的关键字和类型
        /// </summary>
        /// <returns></returns>
        public string[] GetKey()
        {
            return this.GetKey(this.entity.getTableName());
        }


        /// <summary>
        /// 获取表的关键字和类型
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public string[] GetKey(string tableName)
        {
            string[] str = new string[2];
            TableInfoStruc entity = this.GetEntityByCondition<TableInfoStruc>("TableName='" + tableName + "' and Substring(PKey,1,1)='Y'");
            if (entity != null)
            {
                str[0] = entity.ColName;
                str[1] = entity.CType;
            }
            return str;
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitysSplitPage()
        {
                string SqlComm=string.Empty;
                try
                {
                    string order = this.Order == "" || this.Order == null ? "" : "( Order by " + this.Order;
                    order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                    SqlComm = "SELECT TOP "+PageSize.ToString()+" * FROM  (   SELECT ROW_NUMBER() OVER"+this.Order+" AS RowNumber,* FROM " +this.entity.getTableName()+ ") A WHERE RowNumber > "+(PageIndex-1)*PageSize;
                    //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                    iSun.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                    om.SqlComm = SqlComm;
                    return om.DatatableToObject();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
        }

        //public virtual System.Data.DataTable GetEntitysSplitPage()
        //{
        //    string SqlComm = string.Empty;
        //    try
        //    {
        //        string order = this.Order == "" || this.Order == null ? "" : "( Order by " + this.Order;
        //        order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
        //        SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (   SELECT ROW_NUMBER() OVER" + this.Order + " AS RowNumber,* FROM " + this.entity.getTableName() + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize;
        //        //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
        //        ZX.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
        //        om.SqlComm = SqlComm;
        //        return om.);
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return null;
        //    }
        //}

        /// <summary>
        /// 执行 Sql Command
        /// </summary>
        /// <param name="SqlCommand">Sql命令行</param>
        /// <returns></returns>
        public int RunSqlCommand(string SqlCommand)
        {
            return (new iSun.DAL.DBExtend.DbSql()).RunSqlCommand(SqlCommand);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SqlCommand"></param>
        /// <param name="para"></param>
        /// <returns></returns>
        public int RunSqlCommand(string SqlCommand, System.Data.IDbDataParameter[] para)
        {
            return (new iSun.DAL.DBExtend.DbSql()).ExecuteSql(SqlCommand, para);
        }


        /// <summary>
        /// 执行 Sql Command
        /// </summary>
        /// <param name="SqlCommand"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int RunSqlCommand(string SqlCommand, out string msg)
        {
            msg = "";
            try
            {
                return RunSqlCommand(SqlCommand);
            }
            catch (Exception e)
            {
                msg = "信息源:" + e.Source + "/r/n消息:" + e.Message;
                return -1;
            }
        }

        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            return (new iSun.DAL.DBExtend.DbSql()).RunProcedure(storedProcName, parameters, true);

        }

        public int GetRowCount(string Condition)
        {
            return (new iSun.DAL.DBExtend.DbSql()).GetRowCount(this.entity.GetTableName(), Condition);
        }
        #region 相关属性
        public virtual int iTop
        {
            get;
            set;
        }

        public virtual string Order
        {
            get;
            set;
        }

        public virtual string Desc
        {
            get;
            set;
        }

        public virtual int PageIndex
        {
            get;
            set;
        }

        public virtual int PageSize
        {
            get;
            set;
        }
        #endregion

    }
}